<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use think\facade\Filesystem;
use app\manage\model\ConfigGroup;
use app\manage\model\ConfigGroupData;

class GroupData extends AdminBaseController
{
    /*protected $middleware = [
        'login' => ['except' => []]
    ];*/

    public function index($id = 0)
    {
//        var_dump($id);die;

        //得到登录用户身份
        $scopes = '';
        $member_id = 0;

        $id = $id ?: $this->request->get('group_id');
        $ConfigGroup = ConfigGroup::where('config_name', $id)->where('scopes', $scopes)->find();
        if ($ConfigGroup) $whereId = $ConfigGroup['id']; else $whereId = $id;
        $data = ConfigGroupData::getShowData($whereId, null, $member_id, $scopes);
        if (!$data) return '租户数据暂时无法查看';
        return view('', ['show' => $data, 'group_id' => $id]);
    }


    /**
     * 列表
     *
     * @return \think\Response
     */
    public function getconfiglist()
    {

        //得到登录用户身份
//        $scopes = 'common';
        $member_id = 0;

        //搜索条件
        $map = array();
        $map[] = ['a.member_id', '=', $member_id];
//        $map[] = ['a.scopes', '=', $scopes];
        $sort = 'a.sort desc,a.id desc';
        //页数
        $page = input('page/d');
        //条数
        $limit = input('limit/d');
        //时间开始
        $time_start = input('beginTime/s');
        //时间结束
        $time_end = input('endTime/s');
        //订单状态
        $id = input('id/d') ?: null;
        $group_id = input('group_id/s');
        //手机号
        $status = input('status/d') ?: null;


        //订单状态
        if ($id !== null) {
            $map[] = ['a.id', '=', $id];
        }


        if ($status !== null) {
            $map[] = ['a.status', '=', $status];
        }


        //时间区间
        if ($time_start != null) {
            $time_start = strtotime($time_start);
            $map[] = ['a.add_time', '>=', $time_start];
            if ($time_end != null) {
                $time_end = strtotime($time_end);
                $map[] = ['a.add_time', '<=', $time_end];
            }
        } elseif ($time_end != null) {
            $time_end = strtotime($time_end);
            $map[] = ['a.add_time', '<=', $time_end];
            if ($time_start != null) {
                $time_start = strtotime($time_start);
                $map[] = ['a.add_time', '>=', $time_start];
            }
        }
        //取出组合数据字段值
        $ConfigGroup = ConfigGroup::where('config_name', $group_id)->find();
        if ($ConfigGroup) {
            $map[] = ['a.group_id', '=', $ConfigGroup['id']];
        } else {
            $map[] = ['a.group_id', '=', $group_id];
            $ConfigGroup = ConfigGroup::find($group_id);
        }
        if (!$ConfigGroup) return json([
            'code' => 1,
            'msg' => '不存在该数据组',
            'count' => 0,
            'data' => [],
        ]);

        $fields = $ConfigGroup['fields'];
        $configs = json_decode($fields, true);//json串传数组
        //门店列表
        $list = ConfigGroupData::alias('a')
            ->field(['a.*'])
            ->where($map)
            ->page($page, $limit)
            ->order($sort)
            ->select();


        foreach ($list as &$obj) {
            $value = $obj['value'];
            unset($obj['value']);
            $value = json_decode(htmlspecialchars_decode($value), true);

            foreach ($configs as $config) {
                if ($value) {
                    if (isset($value[$config['config_name']])) {
                        if ($config['type'] == 'upload') {

                            $r_textarea = base64_decode($value[$config['config_name']]['value']);
                            //var_dump($r_textarea);die;
                            $value[$config['config_name']]['value'] = json_decode(htmlspecialchars_decode(urldecode($r_textarea)), true);
                        }


                        $obj[$config['config_name']] = $value[$config['config_name']]['value'];
                    } else {
                        $obj[$config['config_name']] = null;
                    }
                } else {
                    $obj[$config['config_name']] = null;
                }
            }

        }
        //echo Db::name('offline_order')->getLastSql();die;//打印最后一条
        //echo Db::table('contract')->getLastSql();die;//打印最后一条sql
        $count = ConfigGroupData::alias('a')
            ->where($map)
            ->count();

        //总数
        //列表数据
        $data = array();
        $data['code'] = 0;
        $data['msg'] = '查询成功';
        $data['count'] = $count;
        $data['data'] = $list;
        return json($data);
    }

    public function add()
    {
        //得到登录用户身份
        $scopes = '';
        $member_id = 0;
        $group_id = $this->request->get('group_id');
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $res = ConfigGroupData::setValues($param, $member_id, $scopes, true);
            if (!$res) return $this->error(ConfigGroupData::getError('设置失败'));
            return $this->success('添加成功');
        }

        //var_dump($id);die;
        $ConfigGroup = ConfigGroup::where('config_name', $group_id)->find();
        if ($ConfigGroup) $data = ConfigGroupData::getShowData($ConfigGroup['id'], null, $member_id, $scopes); else $data = ConfigGroupData::getShowData($group_id, null, $member_id, $scopes);
//        var_dump($data);die;
        return view('edit', ['entity' => null, 'show' => $data, 'group_id' => $group_id]);
    }


    public function edit()
    {
        //得到登录用户身份
        $scopes = '';
        $member_id = 0;

        $group_id = $this->request->get('group_id');
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $res = ConfigGroupData::setValues($param, $member_id, $scopes, true);
            if (!$res) return $this->error(ConfigGroupData::getError('设置失败'));
            return $this->success('更新成功');
        }
        $id = $this->request->get('id');

        $data = ConfigGroupData::find($id);
        $ConfigGroup = ConfigGroup::where('config_name', $group_id)->where('scopes', $scopes)->find();
        if ($ConfigGroup) $ShowData = ConfigGroupData::getShowData($ConfigGroup['id'], $data, $member_id, $scopes); else $ShowData = ConfigGroupData::getShowData($group_id, $data, $member_id, $scopes);

        return view('', ['entity' => $data, 'show' => $ShowData, 'group_id' => $group_id]);
    }


    /**
     * 删除/批量删除
     *
     * @return \think\Response
     */
    public function softdleting()
    {

        //门店ids
        $ids = input('ids/s');
        $ids_array = explode(',', $ids);
        $list = array();
        foreach ($ids_array as $key) {
            //如果存在子配置则不允许删除
//            if(ConfigTab::haveConfig($key)){
//                return 'paramFail';
//            }


            ConfigGroupData::destroy($key);
        }

        //Offline::destroy($ids_array);
        return 'success';
    }


    /**
     * 更改开启状态
     *
     * @return \think\Response
     */
    public function setConfigShow()
    {
        $id = input('id/d');
        $data = ConfigGroupData::find($id);
        if ($data['status'] === 1) {
            $data['status'] = 2;
        } elseif ($data['status'] === 2) {
            $data['status'] = 1;
        };
        $data->save();
        return 'success';
    }


}